package cfluo.study;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Results;
import org.kie.api.event.rule.DebugAgendaEventListener;
import org.kie.api.event.rule.DebugRuleRuntimeEventListener;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import cfluo.study.fact.Message;

public class DroolsTest2 {
	/**
	 * 动态加载规则文件使用kie API
	 */
	@Test
	public void DynamicRulesTest(){
		String rule = "package cfluo.study\r\n";
		rule += "import cfluo.study.fact.Message;\r\n";
		rule += "rule \"Hello World\"\r\n";
		rule += "\twhen\r\n";
		rule += "m : Message( status == Message.HELLO, myMessage : msg )";
		rule += "\tthen\r\n";
		rule += "\t\tSystem.out.println( myMessage );\r\n";
		rule += "\t\tm.setMsg(\"Goodbye cruel world\");\r\n";
		rule += "\t\tm.setStatus( Message.GOODBYE );;\r\n";
		rule += "\t\tupdate( m );;\r\n";
		rule += "end\r\n";
		
		rule += "rule \"GoodBye\"\r\n";
		rule += "\twhen\r\n";
		rule += "Message( status == Message.GOODBYE, myMessage : msg )";
		rule += "\tthen\r\n";
		rule += "\t\tSystem.out.println( 2+\":\"+myMessage );\r\n";
		rule += "end\r\n";
		
		KieServices kieServices = KieServices.Factory.get();
	    KieFileSystem kfs = kieServices.newKieFileSystem();
	    kfs.write( "src/main/resources/rules/ruless.drl",rule.getBytes());
	    KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll();
	    Results results = kieBuilder.getResults();
	    if( results.hasMessages( org.kie.api.builder.Message.Level.ERROR ) ){
	        System.out.println( results.getMessages() );
	        throw new IllegalStateException( "### errors ###" );
	    }
	    KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId() );
	    KieBase kieBase = kieContainer.getKieBase();
	    KieSession ksession = kieBase.newKieSession();
	    
	    Message message = new Message();
        message.setMsg("Hello World");
        message.setStatus(Message.HELLO);
        
        Message message2 = new Message();
		message2.setStatus(Message.HELLO);
		message2.setMsg("hi world!");
     /*   ksession.addEventListener( new DebugAgendaEventListener() );
        ksession.addEventListener( new DebugRuleRuntimeEventListener() );*/
        ksession.insert(message);
        ksession.insert(message2);
        ksession.fireAllRules();

	}
}
